package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;
import helpers.UrlHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Page;


public class HomeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String uri = request.getRequestURI();
		String hostname = UrlHelper.getServerUrl(request);
		
		String pageJsp = "/pages/home.jsp";
		Page page = new Page();
		
		if (!uri.equalsIgnoreCase("/")) {
			String url = "http://www.roseindia.net" + uri;
			pageJsp = "/pages/info.jsp";
			
			page = FileHelper.getPageByFileName(url);
			
			if (page == null) {
				if (url.contains("/tags/")) {
					page = CrawlerHelper.getTag(url);
					page.setUrl(url);
				} else {
					page = CrawlerHelper.getContent(url);
					page.setUrl(url);
				}
				
				if (!page.getContent().isEmpty()) {
					FileHelper.saveCurrentPage(page);
				}
				
			} else {
				if (page.getContent().isEmpty()) {
					System.out.println("cached");
					if (url.contains("/tags/")) {
						page = CrawlerHelper.getTag(url);
						page.setUrl(url);
					} else {
						page = CrawlerHelper.getContent(url);
						page.setUrl(url);
					}
					
					if (!page.getContent().isEmpty()) {
						FileHelper.saveCurrentPage(page);
					}
					
				}
				if (url.contains("/tags/")) {
					pageJsp = "/pages/tags.jsp";
				}
			}
		}
		
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher(pageJsp).forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
		
	}
}
